package com.sunwayworld.basemodule.samplemanage.samplestaging.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.samplemanage.samplestaging.dao.LimsSampleStagingDao;
import com.sunwayworld.basemodule.samplemanage.samplestaging.bean.LimsSampleStagingBean;
import com.sunwayworld.basemodule.samplemanage.samplestaging.service.LimsSampleStagingService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsSampleStagingServiceImpl implements LimsSampleStagingService {

    @Autowired
    private LimsSampleStagingDao limsSampleStagingDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsSampleStagingDao getDao() {
        return limsSampleStagingDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsSampleStagingBean limsSampleStaging = jsonWrapper.parseUnique(LimsSampleStagingBean.class);
        limsSampleStaging.setId(ApplicationContextHelper.getNextIdentity());

        String stagingCode = ApplicationContextHelper.getNextSequence(getDao().getTable(),"B");
        limsSampleStaging.setStagingCode(stagingCode);

        getDao().insert(limsSampleStaging);
        return limsSampleStaging.getId();
    }

    @Override
    public JSONObject changeStatus(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();

        String status = wrapperBean.getParamValue("status");
        List<LimsSampleStagingBean> datas = wrapperBean.parse(LimsSampleStagingBean.class);
        if (StringUtils.isBlank(status) || datas.isEmpty()) {
            return req;
        }
        List<Long> ids = datas.stream().map(LimsSampleStagingBean::getId).collect(Collectors.toList());
        LimsSampleStagingBean update = new LimsSampleStagingBean();
        update.setStatus(status);
        getDao().updateByIds(update, ids, "status");

        return req;
    }
}
